"use client"

import { View, Text, StyleSheet, TextInput, TouchableOpacity, ScrollView, Platform } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { ArrowLeft, X, Search } from "lucide-react-native"
import { useRouter } from "expo-router"
import { useState, useEffect } from "react"
import { theme } from "../constants/theme"
import Animated, { FadeInDown } from "react-native-reanimated"

// 模拟的单词数据库
const WORD_DATABASE = [
    { word: "one", type: "num", meaning: "一" },
    { word: "one of", type: "phrase", meaning: "其中之一" },
    { word: "oneself", type: "pron", meaning: "自己；亲自" },
    { word: "onerous", type: "adj", meaning: "繁重的；艰巨的；费力的" },
    { word: "one-way", type: "adj", meaning: "单程的；单行道的；单方面的" },
    { word: "one day", type: "phrase", meaning: "有一天；总有一天" },
    { word: "one third", type: "phrase", meaning: "三分之一" },
    { word: "one-sided", type: "adj", meaning: "片面的；一边倒的；偏向一边的" },
    { word: "one by one", type: "phrase", meaning: "一个接一个" },
    { word: "one-to-one", type: "adj", meaning: "一对一的；对应的" },
    { word: "apple", type: "n", meaning: "苹果" },
    { word: "banana", type: "n", meaning: "香蕉" },
    { word: "cat", type: "n", meaning: "猫" },
    { word: "dog", type: "n", meaning: "狗" },
    { word: "elephant", type: "n", meaning: "大象" },
    { word: "fish", type: "n", meaning: "鱼" },
    { word: "giraffe", type: "n", meaning: "长颈鹿" },
    { word: "horse", type: "n", meaning: "马" },
    { word: "ice cream", type: "n", meaning: "冰淇淋" },
    { word: "juice", type: "n", meaning: "果汁" },
]

export default function SearchScreen() {
    const router = useRouter()
    const [searchText, setSearchText] = useState("")
    const [searchResults, setSearchResults] = useState([])

    // 搜索功能
    useEffect(() => {
        // 如果搜索文本为空，清空结果
        if (!searchText.trim()) {
            setSearchResults([])
            return
        }

        // 根据输入文本过滤单词
        const filteredResults = WORD_DATABASE.filter((item) => item.word.toLowerCase().includes(searchText.toLowerCase()))

        setSearchResults(filteredResults)
    }, [searchText])

    const handleClear = () => {
        setSearchText("")
        setSearchResults([])
    }

    const handleBack = () => {
        router.back()
    }

    // 高亮显示匹配的文本
    const highlightText = (text, query) => {
        if (!query) return text

        const lowerText = text.toLowerCase()
        const lowerQuery = query.toLowerCase()

        if (!lowerText.includes(lowerQuery)) return text

        const startIndex = lowerText.indexOf(lowerQuery)
        const endIndex = startIndex + query.length

        return (
            <>
                {text.substring(0, startIndex)}
                <Text style={styles.highlight}>{text.substring(startIndex, endIndex)}</Text>
                {text.substring(endIndex)}
            </>
        )
    }

    return (
        <SafeAreaView style={styles.container} edges={["top"]}>
            {/* 头部搜索栏 */}
            <View style={styles.header}>
                <TouchableOpacity onPress={handleBack} style={styles.backButton}>
                    <ArrowLeft size={24} color={theme.colors.neutral.black} />
                </TouchableOpacity>
                <View style={styles.searchContainer}>
                    <Search size={20} color={theme.colors.neutral.gray} style={styles.searchIcon} />
                    <TextInput
                        style={styles.searchInput}
                        placeholder="输入单词"
                        value={searchText}
                        onChangeText={setSearchText}
                        autoFocus
                        placeholderTextColor={theme.colors.neutral.gray}
                    />
                    {searchText.length > 0 && (
                        <TouchableOpacity onPress={handleClear} style={styles.clearButton}>
                            <X size={16} color={theme.colors.neutral.gray} />
                        </TouchableOpacity>
                    )}
                </View>
            </View>

            {/* 搜索结果 */}
            <ScrollView style={styles.resultsContainer} showsVerticalScrollIndicator={false}>
                {searchResults.length > 0 ? (
                    searchResults.map((item, index) => (
                        <Animated.View
                            key={item.word}
                            entering={FadeInDown.delay(index * 50).springify()}
                            style={styles.resultItem}
                        >
                            <View style={styles.wordContainer}>
                                <Text style={styles.word}>{highlightText(item.word, searchText)}</Text>
                                <Text style={styles.type}>{item.type}</Text>
                            </View>
                            <Text style={styles.meaning}>{item.meaning}</Text>
                        </Animated.View>
                    ))
                ) : searchText.length > 0 ? (
                    <View style={styles.emptyResults}>
                        <Text style={styles.emptyResultsText}>没有找到相关单词</Text>
                    </View>
                ) : null}

                {searchResults.length > 0 && (
                    <View style={styles.footer}>
                        <Text style={styles.footerText}>目前支持 6.37万 个单词搜索，更多单词正在加班更新中...</Text>
                    </View>
                )}
            </ScrollView>
        </SafeAreaView>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: theme.colors.neutral.white,
    },
    header: {
        flexDirection: "row",
        alignItems: "center",
        paddingHorizontal: theme.spacing.lg,
        paddingVertical: theme.spacing.md,
        borderBottomWidth: 1,
        borderBottomColor: theme.colors.neutral.lightGray,
        backgroundColor: theme.colors.neutral.white,
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.5,
                shadowRadius: 4,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    backButton: {
        padding: theme.spacing.sm,
        marginRight: theme.spacing.md,
    },
    searchContainer: {
        flex: 1,
        flexDirection: "row",
        alignItems: "center",
        backgroundColor: theme.colors.neutral.lightGray,
        borderRadius: theme.borderRadius.large,
        paddingHorizontal: theme.spacing.md,
    },
    searchIcon: {
        marginRight: theme.spacing.sm,
    },
    searchInput: {
        flex: 1,
        height: 40,
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.black,
    },
    clearButton: {
        padding: theme.spacing.sm,
    },
    resultsContainer: {
        flex: 1,
    },
    resultItem: {
        padding: theme.spacing.lg,
        borderBottomWidth: 1,
        borderBottomColor: theme.colors.neutral.lightGray,
    },
    wordContainer: {
        flexDirection: "row",
        alignItems: "center",
        marginBottom: theme.spacing.xs,
    },
    word: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
        marginRight: theme.spacing.sm,
    },
    highlight: {
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.bold,
    },
    type: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.gray,
        fontStyle: "italic",
    },
    meaning: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.darkGray,
    },
    emptyResults: {
        padding: theme.spacing.xxxl,
        alignItems: "center",
        justifyContent: "center",
    },
    emptyResultsText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.gray,
    },
    footer: {
        padding: theme.spacing.xl,
        alignItems: "center",
    },
    footerText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.gray,
        textAlign: "center",
    },
})

